<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title></title>
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
  <link href="css/mui.min.css" rel="stylesheet" />
  <style type="text/css">
    html,body,.mui-content{
      height: 100%;
      width: 100%;
      background-color: #FFFFFF;
    }
    .logo-img{
      width:100%;
    }
    .logo-img03{
      width: 24.4%;
      position:absolute;
      top:40%;
      left:38%
    }
    .logoin-title{
      text-align: center;
      font-size: 20px;
      color: #FD7673;
    }
    /**/
    .mui-input-group:before{
      height: 0;
    }
    .mui-input-group:after{
      height: 0;
    }
    .area {
      margin: 20px auto 0px auto;
    }

    .mui-input-group {
      margin-top: 30px;
    }

    .mui-input-group:first-child {
      margin-top: 20px;
    }

    .mui-input-group label {
      width: 22%;
    }

    .mui-input-row label~input,
    .mui-input-row label~select,
    .mui-input-row label~textarea {
      width: 78%;
    }

    .mui-checkbox input[type=checkbox],
    .mui-radio input[type=radio] {
      top: 6px;
    }


    .mui-btn {
      padding: 10px;
    }

    .link-area {
      display: block;
      margin-top: 25px;
      text-align: center;
    }

    .spliter {
      color: #bbb;
      padding: 0px 8px;
    }
    .mui-content-padded, .check-update{
      width: 70%;
      margin: 25px auto 0;
      text-align: center;
    }
    .check-btn{
      color:RGB(253,118,115);
      border: 1px solid RGB(253,118,115);
    }
    #login{
      color:white;
      background-color: RGB(253,118,115);
      border: 1px solid RGB(253,118,115);
    }
    .footerDiv{
      margin: 80px auto 0;
      width: 100%;
    }
    .name-vison{
      text-align: center;
      margin: 0;
      padding: 0;
      color:RGB(253,118,115);
    }
   /*.versionInfoDiv{*/
     /*width: 80%;*/
     /*height: 200px;*/
     /*overflow: scroll;*/
   /*}*/
    /*.mui-scroll-wrapper{*/
      /*position: relative;*/
      /*height: 300px;*/
      /*overflow: auto;*/
    /*}*/
    /*.mui-scroll{*/
      /*height: 100%;*/
      /*overflow: auto;*/
    /*}*/
/*.muiSpan{*/
  /*display: block;*/
  /*width: 80%;*/
  /*height: 400px;*/
  /*font-weight: bold;*/
/*}*/
  </style>
  <!--<script src="https://www.w3cways.com/demo/vconsole/vconsole.min.js?v=2.2.0"></script>-->
  <script src="js/mui.min.js"></script>
  <script type="text/javascript">
    var width = document.documentElement.clientWidth;
    window.localStorage.setItem('width',width);
    mui.init();
  </script>
</head>

<body>
<div class="mui-content">
  <div class="logo-header" style='position:relative'>
    <img class="logo-img" src="./images/logoin.png" alt="" />
    <img src="./images/logo_03.png" class='logo-img03' alt="" />
    <p class="logoin-title">店内经营管理系统</p>
  </div>
  <form id='login-form' class="mui-input-group">
    <div class="mui-input-row">
      <label>账号</label>
      <input id='account' type="text" class="mui-input-clear mui-input" placeholder="请输入账号">
    </div>
    <div class="mui-input-row">
      <label>密码</label>
      <input id='password' type="password" class="mui-input-clear mui-input" placeholder="请输入密码">
    </div>
  </form>
  <!--<form class="mui-input-group">
    <ul class="mui-table-view mui-table-view-chevron">
      <li class="mui-table-view-cell">
        自动登录
        <div id="autoLogin" class="mui-switch">
          <div class="mui-switch-handle"></div>
        </div>
      </li>
    </ul>
  </form>-->
  <div class="mui-content-padded">
    <button id='login' data-loading-text="登录中" class="mui-btn mui-btn-block ">登录</button>
  </div>
  <div class="check-update">
    <!--<a  class="check-btn"></a>-->
    <button class='check-btn mui-btn mui-btn-block'   >检查更新</button>
  </div>
  <div class='footerDiv'>
    <p class="name-vison">商户：<span class="wareName"></span></p>
    <p class="name-vison">版本号：<span class="vision"></span></p>
  </div>

</div>

</div>
<script src="config.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
  var originData = {
    shops: [],
    userName: '',
    currentShop: ''
  };
  var isSubmit = false;
  var form = {
    logName: '',
    password: ''
  };
  var wgtVer = ''  //当前版本
  var downWgtWait
  var newVersion = '', //新版本
    downUrl='' ; //下载地址
  var newVersionInfo='';
  var allVersionInfo='';
  mui.plusReady(function() {
    bindEvent();
    mui('.mui-scroll-wrapper').scroll({
      scrollY: true,
      bounce: true,
      deceleration: 0.0005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006，
    });
    checkUpdate()
    getStoreList()
    document.querySelector('.wareName').innerText=config.wareName
  });
  //检查更新
  function checkUpdate(type) {
    plus.runtime.getProperty(plus.runtime.appid, function(inf) {
      wgtVer = inf.version;
      // console.log(wgtVer);
      document.querySelector('.vision').innerText = wgtVer
    });
    config.ajax({
      url: config.basePath + '/app/checkLastByVersion',
      type: 'GET',
      success: function(res) {
        // console.log(JSON.stringify(res))
        // console.log("checkUpdate")
        if(res.result === 1) {
          newVersionInfo=res.version.versionInfo.split('\n');
          newVersion = res.version.version;
          if(res.version.version !== wgtVer) {
            downUrl = config.imgPath + res.version.path;
            ifDown(1)
            // var btnArray2=['取消'];
            // var infostr2='<div class="versionInfoDiv"><span class="muiSpan">[{"appId":43,"version":"1.3.50","versionInfo":"1、测试信息\\n2、测试2"},{"appId":44,"version":"1.3.52","versionInfo":"1、增加版本更新描述功能；\\n2、修复已知的bug；"}][{"appId":43,"version":"1.3.50","versionInfo":"1、测试信息\\n2、测试2"},{"appId":44,"version":"1.3.52","versionInfo":"1、增加版本更新描述功能；\\n2、修复已知的bug；"}][{"appId":43,"version":"1.3.50","versionInfo":"1、测试信息\\n2、测试2"},{"appId":44,"version":"1.3.52","versionInfo":"1、增加版本更新描述功能；\\n2、修复已知的bug；"}][{"appId":43,"version":"1.3.50","versionInfo":"1、测试信息\\n2、测试2"},{"appId":44,"version":"1.3.52","versionInfo":"1、增加版本更新描述功能；\\n2、修复已知的bug；"}][{"appId":43,"version":"1.3.50","versionInfo":"1、测试信息\\n2、测试2"},{"appId":44,"version":"1.3.52","versionInfo":"1、增加版本更新描述功能；\\n2、修复已知的bug；"}]</span></div>';
            // var str='<div class="mui-scroll-wrapper"><div class="mui-scroll"><span class="muiSpan">[{"appId":43,"version":"1.3.50","versionInfo":"1、测试信息\\n2、测试2"},{"appId":44,"version":"1.3.52","versionInfo":"1、增加版本更新描述功能；\\n2、修复已知的bug；"}][{"appId":43,"version":"1.3.50","versionInfo":"1、测试信息\\n2、测试2"},{"appId":44,"version":"1.3.52","versionInfo":"1、增加版本更新描述功能；\\n2、修复已知的bug；"}][{"appId":43,"version":"1.3.50","versionInfo":"1、测试信息\\n2、测试2"},{"appId":44,"version":"1.3.52","versionInfo":"1、增加版本更新描述功能；\\n2、修复已知的bug；"}][{"appId":43,"version":"1.3.50","versionInfo":"1、测试信息\\n2、测试2"},{"appId":44,"version":"1.3.52","versionInfo":"1、增加版本更新描述功能；\\n2、修复已知的bug；"}][{"appId":43,"version":"1.3.50","versionInfo":"1、测试信息\\n2、测试2"},{"appId":44,"version":"1.3.52","versionInfo":"1、增加版本更新描述功能；\\n2、修复已知的bug；"}]</span>是个好框架，确认？</div></div>';
            //
            // mui.confirm(str, '版本信息', btnArray2, function(e) {
            //   if(e.index == 0) {
            //
            //   }
            // },'div')
          } else {
            if(type) {
              ifDown(2)
            }

          }
        }
      }
    })
  }
  //是否下载
  function ifDown(num) {
    // console.log("11111")
    config.ajax({
      url:config.basePath + '/app/checkAllVersion',
      type: 'GET',
      success: function(res){
        // console.log("allversion:"+JSON.stringify(res));
        if(res.result === 1) {
          allVersionInfo=JSON.parse(JSON.stringify(res.appVersions));
          // console.log(JSON.stringify(allVersionInfo));
          var infostr='';
          var iteminfo='';
          var itemstr='';
          for(var i=allVersionInfo.length-1;i>=0;i--){
            infostr += allVersionInfo[i].version + "版本:\n";
            iteminfo=allVersionInfo[i].versionInfo.split('\n');
            itemstr='';
            if(iteminfo.length>0){
              for(var j=0;j<iteminfo.length;j++){
                itemstr+=('    '+iteminfo[j]+'\n');
              }
              infostr += itemstr;
            }
          }
          // console.log(infostr);
          if(num===1){//未安装最新版本
            var btnArray = ['取消','更新'];
            var infostr1='当前版本：'+wgtVer+'\n'+'\n'+infostr;
            mui.confirm(infostr1, '版本信息', btnArray, function(e) {
              if(e.index == 1) {
                downWgt(downUrl)
              }
            });
          }else if(num===2){//已安装最新版本
            var infostr2='当前已是最新版本：'+newVersion+'\n'+'\n'+infostr;
            var btnArray2 = ['返回'];
            mui.confirm(infostr2, '版本信息', btnArray2, function(e) {
              if(e.index == 0) {

              }
            })
          }
        }

      },
    });

  }
  //下载更新
  function downWgt(wgtUrl) {
    downWgtWait = plus.nativeUI.showWaiting("下载更新文件...");
    var dtask = plus.downloader.createDownload(wgtUrl, {
      filename: "_doc/update/"
    }, function(d, status) {
      plus.nativeUI.closeWaiting();
      if(status == 200) {
        console.log(d.filename)
        installWgt(d.filename); // 安装包
      } else {
        plus.nativeUI.alert("下载更新失败！");
      }
    });
    dtask.addEventListener('statechanged', onStateChanged, false)
    dtask.start()
  }
  //监听下载进度
  function onStateChanged(task, status) {
    if(status != null && status == 200 && task.state != null) {
      var a = task.downloadedSize / task.totalSize * 100;
      downWgtWait.setTitle("下载更新文件..." + parseInt(a) + "%");
    }
  }
  //安装更新
  function installWgt(path) {
    plus.nativeUI.showWaiting("安装更新文件...");
    plus.runtime.install(path, {force:true}, function() {
      plus.nativeUI.closeWaiting();
      plus.nativeUI.alert("应用资源更新完成！", function() {
        plus.runtime.restart();
      });
    }, function(e) {
      plus.nativeUI.closeWaiting();
      console.log("安装更新文件失败[" + e.code + "]：" + e.message);
      plus.nativeUI.alert("安装更新文件失败[" + e.code + "]：" + e.message);
    });
  }
  // 获取所有门店列表
  function getStoreList() {
    var vm = this
    config.ajax({
      url: config.basePath + '/shops',
      headers: {
        'Content-Type': 'application/json'
      },
      crossDomain: true,
      dataType: 'json',
      type: 'GET',
      success: function(res) {
        if(res.result === 1) {
          originData.allShops = res.merchantStoreList
        }
      }
    });
  }

  function bindEvent() {
    mui('.mui-content-padded').on('tap', '#login', function() {
      mui('#account')[0].blur();
      mui('#password')[0].blur();
      getFormValue();
      var validateName = validateInput(form.logName, {
        required: true
      }, '请输入用户名!');
      var validatePassword = validateInput(form.password, {
        required: true
      }, '请输入密码!');
      if(validateName && validatePassword) {
        loginIn();
      }
    });

    mui.back = function() {
      var btnArray = ['是', '否'];
      mui.confirm('你确定退出应用？', '退出', btnArray, function(e) {
        if(e.index == 0) {
          plus.runtime.quit();
        } else {}
      });
    }
    mui('.check-btn')[0].addEventListener('tap',function(){
      checkUpdate(1)
    })
  }

  function loginIn() {
    if(isSubmit) {
      return;
    }
    mui('#login').button('loading');
    isSubmit = true;
    config.ajax({
      url: config.basePath + '/login/doLogin',
      headers: {
        'Content-Type': 'application/json'
      },
      crossDomain: true,
      dataType: 'json',
      type: 'POST',
      data: form,
      success: function(res) {
        if(res.result === 1) {
          originData.shops = res.info.shops;
          originData.pages = res.info.phonePages
          originData.userName = res.info.info.userName;
          originData.currentShop = res.info.currentShop;
          plus.nativeUI.toast('登陆成功');
          LoginSuccess();
          isSubmit = false;
        } else {
          isSubmit = false;
          mui.toast(res.errormsg);
        }
        setTimeout(function() {
          mui('#login').button('reset');
        }, 0)
      },
      error:function() {
        mui.toast('登陆超时！')
        mui('#login').button('reset');
      }
    });
    setTimeout(function(){
      if(originData.shops===[]) {
        isSubmit = false;
        plus.nativeUI.toast('登陆超时，请重新登录');
      }
    },5000)
  }

  function getFormValue() {
    form.logName = mui('#account')[0].value;
    form.password = mui('#password')[0].value;
  }

  function validateInput(val, rules, message) {
    if(rules.required === true && val === '') {
      plus.nativeUI.toast(message);
      return false;
    }
    return true;
  }

  function LoginSuccess() {
    originData.shopObjs = []
    window.localStorage.setItem('isShow',0)
    console.log(JSON.stringify(originData))
    if(localStorage.getItem('selectShop')) {
      for(var i = 0; i < originData.shops.length; i++) {
        for(var j = 0; j < originData.allShops.length; j++) {
          if(originData.shops[i] === originData.allShops[j].storeId) {
            originData.shopObjs.push(originData.allShops[j]);
          }
        }
      }
      console.log(121)
      mui.openWindow({
        url: 'switch/switch.html',
        id: 'switch-link',
        styles: {
          titleNView: {
            titleText: '切换门店',
            titleColor: "#FFFFFF",
            titleSize: "17px",
            backgroundColor: "#FF6800",
            autoBackButton: true,
            splitLine: {
              color: "#CCCCCC",
              height: "1px"
            }
          }
        },
        extras: {
          originData: originData
        }
      });
    } else {
      mui.openWindow({
        url: 'index.html',
        id: 'index',
        extras: {
          originData: originData,
        }
      });
    }

  }
</script>
</body>

</html>